﻿using Bird.Core.Data;
using Bird.Core.Domain.Members;
using Bird.Services.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bird.Services.Members
{
    public class MemberService : IMemberService
    {
        IRepository<Member> _repository;
        IEventPublisher _eventPublisher;

        public MemberService(IRepository<Member> repository, IEventPublisher eventPublisher)
        {
            _repository = repository;
            _eventPublisher = eventPublisher;
        }

        public void AddMember(Member member)
        {
            _repository.Insert(member);
            _eventPublisher.EntityInserted(member);
        }

        public void DeleteMember(Member member)
        {
            _repository.Delete(member);
            _eventPublisher.EntityDeleted(member);
        }

        public void UpdateMember(Member member)
        {
            _repository.Update(member);
            _eventPublisher.EntityUpdated(member);
        }

        public void DisableMember(Member member)
        {
            member.Active = false;
            _repository.Update(member);
            _eventPublisher.EntityUpdated(member);
        }

        public void EnableMember(Member member)
        {
            member.Active = true;
            _repository.Update(member);
            _eventPublisher.EntityUpdated(member);
        }

        public Member GetMemberByUsernameOrEmail(string usernameOrEmail)
        {
            if (string.IsNullOrEmpty(usernameOrEmail))
                throw new ArgumentNullException("usernameOrEmail");
            if (usernameOrEmail.Contains("@"))
                return _repository.Table.Where(x => string.Compare(usernameOrEmail, x.Email, true) == 0).First();
            else
                return _repository.Table.Where(x => string.Compare(usernameOrEmail, x.Username, true) == 0).First();
        }

        public Member GetMemberById(int id)
        {
            return _repository.GetById(id);
        }

        public Member GetMemberByGuid(Guid guid)
        {
            return _repository.Table.Where(x => x.MemberGuid == guid).First();
        }
    }
}
